package cheme.ProcessModel.Cmds;

import org.eclipse.gef.commands.Command;

import cheme.ProcessModel.IChild;
import cheme.ProcessModel.IParent;

public class MoveCmd extends Command
{
	private IChild childToMove = null;
	private IParent originalParent = null;
	private IParent newParent = null;
	private int oldIndex;
	private int newIndex;

	public MoveCmd(IChild childToMove, IChild childAfter, IParent originalParent, IParent newParent)
	{
		super();
		this.childToMove = childToMove;
		this.originalParent = originalParent;
		this.newParent = newParent;

		oldIndex = originalParent.getChildren().indexOf(childToMove);
		newIndex = newParent.getChildren().indexOf(childAfter);
	}
	
	public MoveCmd(IChild childToMove, IParent parent, int newIndex)
	{		
		this.childToMove = childToMove;
		this.originalParent = newParent = parent;
		this.oldIndex = originalParent.indexOf(childToMove);
		this.newIndex = newIndex;
		
		if (this.newIndex > oldIndex)
		{
			this.newIndex--; //this is because the child is deleted before it is added
		}
	}
	
	public MoveCmd(IChild childToMove, IParent originalParent, IParent newParent, int newIndex)
	{		
		this.childToMove = childToMove;
		this.originalParent = originalParent;
		this.newParent = newParent;
		this.oldIndex = originalParent.indexOf(childToMove);
		this.newIndex = newIndex;
		
		if (this.newIndex > oldIndex)
		{
			this.newIndex--; //this is because the child is deleted before it is added
		}
	}

	public void execute()
	{
		originalParent.remove(childToMove);
		newParent.add(childToMove, newIndex);
	}
	
	public void redo()
	{
		execute();
	}

	public void undo()
	{
		newParent.remove(childToMove);
		originalParent.add(childToMove, oldIndex);
	}
}
 